import {
  login as _login,
  getUserInfo as _getUserInfo,
  wxLogin as _wxLogin,
  logout as _logout,
  getWxCode,
  getUserProfile,
  ILoginForm,
} from '@/api/login'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { toast } from '@/utils/toast'
import {
  IUserInfoVo,
  IUserLogin,
  ICheckUserToken,
  IUpdateUserAvatar,
  IUpdateInfo,
} from '@/api/login.typings'
import { http } from '@/utils/http'
import { useAuthHeaders, setToken } from '@/utils/token'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL

// 初始化状态
const userInfoState: IUserInfoVo = {
  nickname: '',
  avatarUrl: '/static/images/default-avatar.png',
  gender: true,
  province: '',
  city: '',
  country: '',
  email: '',
  platform: '',
  openId: '',
  unionId: '',
  token: '',
  id: null,
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<IUserInfoVo>({ ...userInfoState })
    // 设置用户信息（适配新结构）
    const setUserInfo = (val: Partial<IUserInfoVo>) => {
      // 合并传入的值和默认值
      const newUserInfo = {
        ...userInfoState,
        ...val,
        // 确保头像有默认值
        avatarUrl: val.avatarUrl || userInfoState.avatarUrl,
      }

      userInfo.value = newUserInfo
    }
    const updateUserAvatar = async (avatar: IUpdateUserAvatar) => {
      const res = await http.put<IUserInfoVo>(
        `${API_BASE_URL}/api/v1/user/avatar`,
        avatar,
        {},
        useAuthHeaders(),
      )
      return getUserInfo(avatar.id)
    }
    const updateUser = async (user: IUpdateInfo) => {
      const res = await http.put<IUserInfo>(
        `${API_BASE_URL}/api/v1/user`,
        user,
        {},
        useAuthHeaders(),
      )
      return getUserInfo(user.id)
    }
    /**
     * 获取最新的用户信息
     */
    const getUserInfo = async (userId?: string | number) => {
      try {
        const id = userId || userInfo.value.id
        if (!id) {
          console.error('无法获取用户信息：缺少用户ID')
          return
        }
        // console.log('token为：', useAuthHeaders())
        const res = await http.get<IUserInfoVo>(
          `${API_BASE_URL}/api/v1/user/${id}`,
          {},
          useAuthHeaders(),
        )
        // console.log(res)
        if (res.code === 200) {
          setUserInfo(res.data)
          return res.data
        } else {
          console.error(`获取用户信息失败: ${res.msg}`)
          toast.error(`获取用户信息失败: ${res.msg}`)
          return null
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
        toast.error('获取用户信息失败，请检查网络')
        return null
      }
    }
    // 删除用户信息
    const removeUserInfo = () => {
      userInfo.value = { ...userInfoState }
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    }
    /**
     * 退出登录 并 删除用户信息
     */
    const logout = async () => {
      // _logout()
      removeUserInfo()
    }
    /**
     * 微信登录
     */
    const wxLogin = async () => {
      // 获取微信小程序登录的code
      const [loginRes, profileRes] = await Promise.all([getWxCode(), getUserProfile()])
      console.log('loginRes', loginRes)
      console.log('profileRes', profileRes)
      const loginRequest: ILoginForm = {
        userInfo: {
          nickname: profileRes.userInfo.nickName,
          avatarUrl: profileRes.userInfo.avatarUrl,
          gender: '',
          province: '',
          city: '',
          country: '',
          email: '',
        },
        iv: profileRes.iv,
        encryptedData: profileRes.encryptedData,
        code: loginRes.code,
      }
      const res = await _wxLogin(loginRequest)
      console.log('登录返回报文', res)
      if (res.code === 200) {
        uni.setStorageSync('userInfo', res.data.userInfo)
        setToken(res.data.token)
        setUserInfo(res.data.userInfo)
        return true
      } else {
        return false
      }
    }

    return {
      userInfo,
      getUserInfo,
      setUserInfo,
      updateUser,
      wxLogin,
      updateUserAvatar,
      logout,
    }
  },
  {
    persist: true,
  },
)
